/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */
package org.jaxson.struts.encoder.csv;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Joe Maisel
 *
 */
public class CsvAnnotationCache
{
	private static final Log lager = LogFactory.getLog(CsvAnnotationCache.class);
	private static final Map<Class<?>, List<CsvFieldDescriptor>> csvFields = new HashMap<Class<?>, List<CsvFieldDescriptor>>();
	
	public static class CsvFieldDescriptor
	{
		protected CsvFieldDescriptor(CsvData ann, Class<?> type, Method getter, String propertyName )
		{
			this.annotation = ann;
			this.type = type;
			this.getter = getter;
			this.propertyName = propertyName;
		}
		
		public CsvData annotation;
		public Class<?> type;
		public Method getter;
		public String propertyName;
	}
	
	@SuppressWarnings("unchecked")
	public static List<CsvFieldDescriptor> get( Class<?> cls ){
		return csvFields.get(cls) == null?new ArrayList():csvFields.get(cls);
	}
	
	public static void parse( Class<?> cls ) throws SecurityException, NoSuchMethodException{
		
		if( csvFields.containsKey(cls) )
			return;
		
		lager.debug( "parsing " + cls );
		
		for( Field f : cls.getDeclaredFields() )
		{
			CsvData ann = f.getAnnotation(CsvData.class);
			
			if( ann == null )
				continue;
			
			String methodName = "get" + f.getName().toUpperCase().charAt(0) + f.getName().substring(1);

			if( !csvFields.containsKey(cls) )
				csvFields.put(cls, new ArrayList<CsvFieldDescriptor>());
			
			csvFields.get( cls ).add(
					new CsvFieldDescriptor( ann, f.getType(), cls.getDeclaredMethod( methodName ), f.getName() ) );
		}
	}
}
